<template>
  <div class="course-list">
    <div class="page-title">课程管理</div>
    
    <!-- 搜索表单 -->
    <a-card class="search-form mb-16">
      <a-form
        ref="searchFormRef"
        :model="searchForm"
        layout="inline"
        @finish="handleSearch"
      >
        <a-form-item label="课程名称" name="courseName">
          <a-input
            v-model:value="searchForm.courseName"
            placeholder="请输入课程名称"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="课程代码" name="courseCode">
          <a-input
            v-model:value="searchForm.courseCode"
            placeholder="请输入课程代码"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="课程类型" name="courseType">
          <a-select
            v-model:value="searchForm.courseType"
            placeholder="请选择课程类型"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="required">必修课</a-select-option>
            <a-select-option value="elective">选修课</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="学科分类" name="subject">
          <a-select
            v-model:value="searchForm.subject"
            placeholder="请选择学科"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="语文">语文</a-select-option>
            <a-select-option value="数学">数学</a-select-option>
            <a-select-option value="英语">英语</a-select-option>
            <a-select-option value="物理">物理</a-select-option>
            <a-select-option value="化学">化学</a-select-option>
            <a-select-option value="生物">生物</a-select-option>
            <a-select-option value="历史">历史</a-select-option>
            <a-select-option value="地理">地理</a-select-option>
            <a-select-option value="政治">政治</a-select-option>
            <a-select-option value="体育">体育</a-select-option>
            <a-select-option value="音乐">音乐</a-select-option>
            <a-select-option value="美术">美术</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 操作按钮 -->
    <div class="action-buttons mb-16">
      <a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          添加课程
        </a-button>
        
        <a-button
          type="primary"
          ghost
          :disabled="!selectedRowKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
        
        <a-button @click="handleSchedule">
          <template #icon>
            <CalendarOutlined />
          </template>
          课程安排
        </a-button>
        
        <a-button @click="handleExport">
          <template #icon>
            <ExportOutlined />
          </template>
          导出课程
        </a-button>
      </a-space>
    </div>
    
    <!-- 课程列表表格 -->
    <a-card class="data-table">
      <a-table
        :columns="columns"
        :data-source="courseList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      >
        <!-- 课程名称列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'courseName'">
            <a @click="handleView(record)" class="course-name-link">
              {{ record.courseName }}
            </a>
          </template>
          
          <!-- 课程类型列 -->
          <template v-else-if="column.key === 'courseType'">
            <a-tag :color="record.courseType === 'required' ? 'red' : 'blue'">
              {{ record.courseType === 'required' ? '必修课' : '选修课' }}
            </a-tag>
          </template>
          
          <!-- 学分列 -->
          <template v-else-if="column.key === 'credits'">
            <a-tag color="green">{{ record.credits }}学分</a-tag>
          </template>
          
          <!-- 课时列 -->
          <template v-else-if="column.key === 'hours'">
            {{ record.hours }}课时
          </template>
          
          <!-- 开课状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-tag
              :color="getStatusColor(record.status)"
              class="status-tag"
            >
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <!-- 选课人数列 -->
          <template v-else-if="column.key === 'enrollmentCount'">
            <a-progress
              :percent="(record.enrollmentCount / record.maxEnrollment) * 100"
              :format="() => `${record.enrollmentCount}/${record.maxEnrollment}`"
              :stroke-color="getEnrollmentColor(record.enrollmentCount, record.maxEnrollment)"
              size="small"
            />
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleViewStudents(record)">
                选课学生
              </a-button>
              <a-popconfirm
                title="确定要删除这个课程吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  CalendarOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 表单引用
const searchFormRef = ref()

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  courseName: '',
  courseCode: '',
  courseType: undefined,
  subject: undefined
})

// 选中的行
const selectedRowKeys = ref([])

// 课程列表
const courseList = ref([
  {
    id: '1',
    courseId: 'COURSE001',
    courseCode: 'CHN101',
    courseName: '小学语文一年级上册',
    subject: '语文',
    courseType: 'required',
    credits: 3.0,
    hours: 72,
    description: '小学一年级语文基础课程，包含拼音、汉字、阅读等内容',
    teacherId: 'T2024001',
    teacherName: '王老师',
    semester: '2024-2025-1',
    status: 'active',
    enrollmentCount: 120,
    maxEnrollment: 150
  },
  {
    id: '2',
    courseId: 'COURSE002',
    courseCode: 'MATH101',
    courseName: '小学数学一年级上册',
    subject: '数学',
    courseType: 'required',
    credits: 3.0,
    hours: 72,
    description: '小学一年级数学基础课程，包含数字认知、基础运算等内容',
    teacherId: 'T2024002',
    teacherName: '李老师',
    semester: '2024-2025-1',
    status: 'active',
    enrollmentCount: 118,
    maxEnrollment: 150
  },
  {
    id: '3',
    courseId: 'COURSE003',
    courseCode: 'ENG101',
    courseName: '小学英语一年级上册',
    subject: '英语',
    courseType: 'required',
    credits: 2.0,
    hours: 48,
    description: '小学一年级英语启蒙课程，包含字母、单词、简单对话',
    teacherId: 'T2024003',
    teacherName: '张老师',
    semester: '2024-2025-1',
    status: 'active',
    enrollmentCount: 95,
    maxEnrollment: 150
  },
  {
    id: '4',
    courseId: 'COURSE004',
    courseCode: 'ART101',
    courseName: '美术基础',
    subject: '美术',
    courseType: 'elective',
    credits: 1.0,
    hours: 24,
    description: '美术基础课程，培养学生的艺术兴趣和创作能力',
    teacherId: 'T2024005',
    teacherName: '陈老师',
    semester: '2024-2025-1',
    status: 'pending',
    enrollmentCount: 30,
    maxEnrollment: 40
  }
])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 4,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '课程代码',
    dataIndex: 'courseCode',
    key: 'courseCode',
    width: 120
  },
  {
    title: '课程名称',
    key: 'courseName',
    width: 200
  },
  {
    title: '学科',
    dataIndex: 'subject',
    key: 'subject',
    width: 100
  },
  {
    title: '课程类型',
    key: 'courseType',
    width: 100,
    align: 'center'
  },
  {
    title: '学分',
    key: 'credits',
    width: 80,
    align: 'center'
  },
  {
    title: '课时',
    key: 'hours',
    width: 80,
    align: 'center'
  },
  {
    title: '任课教师',
    dataIndex: 'teacherName',
    key: 'teacherName',
    width: 120
  },
  {
    title: '学期',
    dataIndex: 'semester',
    key: 'semester',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '选课人数',
    key: 'enrollmentCount',
    width: 150,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    fixed: 'right'
  }
]

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}))

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    active: 'green',
    pending: 'orange',
    suspended: 'red',
    completed: 'blue'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    active: '开课中',
    pending: '待开课',
    suspended: '已暂停',
    completed: '已结课'
  }
  return textMap[status] || '未知'
}

// 获取选课人数进度条颜色
const getEnrollmentColor = (current, max) => {
  const ratio = current / max
  if (ratio >= 0.9) return '#52c41a'
  if (ratio >= 0.7) return '#faad14'
  return '#1890ff'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadCourseList()
}

// 重置搜索
const handleReset = () => {
  searchFormRef.value.resetFields()
  pagination.current = 1
  loadCourseList()
}

// 添加课程
const handleAdd = () => {
  message.info('添加课程功能开发中...')
}

// 查看课程
const handleView = (record) => {
  message.info('查看课程功能开发中...')
}

// 编辑课程
const handleEdit = (record) => {
  message.info('编辑课程功能开发中...')
}

// 查看选课学生
const handleViewStudents = (record) => {
  router.push(`/students?courseId=${record.id}`)
}

// 删除课程
const handleDelete = async (record) => {
  try {
    // 调用删除API
    // await courseApi.deleteCourse(record.id)
    
    message.success('删除成功')
    loadCourseList()
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个课程吗？`,
    onOk: async () => {
      try {
        // 调用批量删除API
        // await courseApi.batchDeleteCourses(selectedRowKeys.value)
        
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadCourseList()
      } catch (error) {
        message.error('批量删除失败')
      }
    }
  })
}

// 课程安排
const handleSchedule = () => {
  message.info('课程安排功能开发中...')
}

// 导出课程
const handleExport = () => {
  message.info('导出功能开发中...')
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadCourseList()
}

// 加载课程列表
const loadCourseList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      ...searchForm,
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 调用API获取数据
    // const response = await courseApi.getCourseList(params)
    // courseList.value = response.data
    // pagination.total = response.total
    
    console.log('加载课程列表', params)
  } catch (error) {
    message.error('加载课程列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadCourseList()
})
</script>

<style scoped>
.course-list {
  padding: 0;
}

.search-form {
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.data-table {
  border-radius: 8px;
}

.course-name-link {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
}

.course-name-link:hover {
  text-decoration: underline;
}

.status-tag {
  border-radius: 12px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .ant-btn {
    width: 100%;
  }
}
</style>